"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : 双机场景：双机重建，主机$GAUSSDATA目录下的文件权限被改动，去掉读权限，进行全量重建，重建失败，给出无访问权限的提示
Create At   : 2020/07/1
@zou_jialiang0505328126
Description :
    1.修改dn1目录权限，去掉读权限
    2.备机重建
    3.恢复权限
Expect      :
    1.修改成功
    2.重建失败，给出无访问权限提示
    3.恢复权限
History     :
    Modified by @li-xin12345 2023/01/16: 优化用例
"""
import unittest
import sys
from yat.test import macro
from yat.test import Node

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant


class Rebuildstandby(unittest.TestCase):
    primary_sh = CommonSH()
    standby_sh = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case055.py start------------')
        self.rootNode = Node(node='PrimaryRoot')
        self.dbUserNode = Node(node='PrimaryDbUser')
        self.dbStandbyNode = Node(node='Standby1DbUser')
        self.DN1_PATH = macro.DB_INSTANCE_PATH
        self.com = Common()
        self.Constant = Constant()

    def test_rebuild_standby(self):
        # remove read permission from dn1
        self.log.info("remove read permission from dn1")
        remove_cmd = "chmod u-r  " + self.DN1_PATH
        self.log.info(remove_cmd)
        self.rootNode.sh(remove_cmd).result()

        # rebuild fail
        status = self.standby_sh.executeGsctl('build', self.Constant.REBUILD_SUCCESS_MSG)
        self.assertFalse(status)

    def tearDown(self):
        self.log.info('this is tearDown')
        self.log.info('recover dn1')

        remove_cmd = "chmod u+r  " + self.DN1_PATH
        self.log.info(remove_cmd)
        self.rootNode.sh(remove_cmd).result()

        # rebuild success
        status = self.standby_sh.executeGsctl('build', self.Constant.REBUILD_SUCCESS_MSG)
        self.assertTrue(status)
